
// 导入模型方法
let { insert, findBygIdAnduId, updateNum, updateSelect, delOne, delMany, findByuId, findCartById } = require('../model/carts');

let { findById } = require('../model/goods');

// 加入购物车
let addFn = async (req, res) => {
  let { uid, gid } = req.body;

  // 查找是否已存在该商品
  let r1 = await findBygIdAnduId(uid, gid);
  if (!r1.length) { // 之前没有添加过该商品到购物车
    await insert({ uid, gid });
    return res.send({ code: 1, message: '添加购物车成功' });
  }

  // 根据商品id 查找商品库存
  let goodsInfo = await findById(r1[0].gid);
  if (!goodsInfo) return res.send({ code: 2, message: '添加失败,商品不存在,请重试' });

  let goods_num = goodsInfo.goods_number;

  if (r1[0].cartnum >= goods_num) return res.send({ code: 2, message: '添加购物车失败,库存不足,请联系商家' });

  await updateNum({ uid, gid }, 1)
  res.send({ code: 1, message: '添加购物车成功' })
}

// 获取用户的购物车信息
let getList = async (req, res) => {
  let { uid } = req.query;
  let r = await findByuId(uid);  
  if (!r.length) return res.send({ code: 1, message: '获取购物车成功', list: [] });
  let rList = [];
  for (let i = 0; i < r.length; i++) {
    let goodsinfo = await findById(r[i].gid);
    rList.push({
      id: r[i]['_id'], // 购物车id
      is_select: r[i].is_select,  // 是否勾选
      cartnum: r[i].cartnum, // 购买数量
      goodsinfo  // 商品详情
    })
  }

  res.send({ code: 1, list: rList })
}

// 移除购物车
let del = async (req, res) => {
  let { opt, id } = req.body;
  if (opt === 'id') {
    await delOne(id);
    return res.send({ code: 1, message: '删除购物车商品成功' });
  }
  if (opt === 'any') {
    await delMany({})
    return res.send({ code: 1, message: '清空购物车商品成功' });
  }

  // 移除选中的购物车商品
  await delMany({ is_select: true })
  return res.send({ code: 1, message: '清空购物车商品成功' });
}


let upSel = async (req, res) => {
  let { opt, id, state } = req.query;
  if (opt === 'id') {
    await updateSelect({ '_id': id }, state);
    return res.send({ code: 1, message: '修改购物车成功' })
  }
  await updateSelect({}, state);
  return res.send({ code: 1, message: '修改购物车成功' })

}

let subCon = async (req, res) => {
  let { id } = req.query;
  // 查找是否已存在该商品
  let r1 = await findCartById(id);
  if (!r1.length) return res.send({ code: 0, message: '修改购物车失败请重试' });
  if (r1[0].cartnum <= 1) return res.send({ code: 0, message: '购物数量最少为1' });
  await updateNum({ '_id': id }, -1);
  return res.send({ code: 1, message: '购物数量修改成功' });
}


module.exports = {
  addFn,
  getList,
  del,
  upSel,
  subCon
}